﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Networking
{
    public class PacketWriter : BinaryWriter
    {
        MemoryStream MemStream = new MemoryStream();
        BinaryFormatter BinFormatter = new BinaryFormatter(); 

        public PacketWriter()
            :base()
        {
            MemStream = new MemoryStream();
            BinFormatter = new BinaryFormatter();
            OutStream = MemStream;
        }

        public byte[] GetBytes()
        {
            Close();
            byte[] data = MemStream.ToArray();

            return data;
        }

        public void WriteObject(object obj)
        {
            BinFormatter.Serialize(MemStream, obj);
        }
    }

    public class PacketReader : BinaryReader
    {
        BinaryFormatter BinFormatter = new BinaryFormatter();

        public PacketReader(byte[] data)
            :base(new MemoryStream(data))
        {
            BinFormatter = new BinaryFormatter();
        }

        public T ReadObject<T>()
        {
            return (T)BinFormatter.Deserialize(BaseStream);
        }
    }
}
